#!/bin/bash

# 切换到脚本所在目录
cd "$(dirname "$0")"

echo "======================================"
echo "   石景山区地图系统 - Vue 3 版本"
echo "======================================"
echo ""

echo "[1] 检查 Node.js 安装..."
if ! command -v node &> /dev/null; then
    echo "[错误] 未检测到 Node.js，请先安装 Node.js"
    echo ""
    echo "下载地址: https://nodejs.org/"
    echo ""
    echo "或使用 Homebrew 安装: brew install node"
    read -p "按任意键退出..."
    exit 1
fi

node -v
echo ""

echo "[2] 检查依赖是否已安装..."
if [ ! -d "node_modules" ]; then
    echo "[提示] 首次运行，正在安装依赖包..."
    echo "这可能需要几分钟时间，请耐心等待..."
    echo ""
    npm install
    if [ $? -ne 0 ]; then
        echo "[错误] 依赖安装失败，请检查网络连接"
        read -p "按任意键退出..."
        exit 1
    fi
    echo ""
    echo "[成功] 依赖安装完成！"
    echo ""
else
    echo "[提示] 依赖已安装，跳过安装步骤"
    echo ""
fi

echo "[3] 清理缓存（避免图标错误）..."
if [ -d "node_modules/.vite" ]; then
    echo "[提示] 清除 Vite 缓存..."
    rm -rf "node_modules/.vite"
    echo "[成功] 缓存已清理"
else
    echo "[提示] 无需清理缓存"
fi
echo ""

echo "[4] 启动开发服务器..."
echo ""
echo "======================================"
echo " 服务器启动中..."
echo " 浏览器将自动打开地图系统"
echo " "
echo " 如果浏览器没有自动打开，请手动访问:"
echo " http://localhost:3000"
echo " "
echo " ✨ 热更新功能已启用！"
echo " 修改代码后会自动刷新浏览器"
echo " "
echo " 常见问题："
echo " - 如果报图标错误，请重新运行此脚本"
echo " - 如果端口被占用，请关闭其他程序"
echo " - 如果热更新不工作，查看控制台错误信息"
echo " "
echo " 按 Ctrl+C 可停止服务器"
echo "======================================"
echo ""

npm run dev

if [ $? -ne 0 ]; then
    echo ""
    echo "[错误] 启动失败！"
    echo ""
    echo "可能的原因："
    echo "1. 端口 3000 被占用"
    echo "2. 依赖安装不完整"
    echo ""
    echo "解决方法："
    echo "1. 关闭占用 3000 端口的程序"
    echo "2. 重新运行此脚本"
    echo "3. 或运行: npm run dev -- --port 3001"
    echo ""
fi

read -p "按任意键关闭..."


